package com.reny.ll.git.base_logic

import android.app.Service
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.kodein.di.DI
import org.kodein.di.DIAware
import org.kodein.di.android.closestDI
import org.kodein.di.diContext

abstract class MService: Service(), DIAware {

    protected val parentDI by closestDI()
    override val diContext = diContext<Service>(this)

    override val di by DI.lazy {
        extend(parentDI)
    }

    override fun onDestroy() {
        super.onDestroy()
        clearJob()
    }

    //对anko协程任务的管理
    private val mJobs = HashSet<Job>()

    private fun clearJob(){
        mJobs.forEach {
            try {
                it.cancel()
            }catch (e:Exception){e.printStackTrace()}
        }
        mJobs.clear()
    }

    private val crashLogger = { throwable: Throwable -> throwable.printStackTrace() }

    fun launch(
        exceptionHandler: ((Throwable) -> Unit)? = crashLogger,
        task: suspend CoroutineScope.() -> Unit
    ): Job {
        val job = GlobalScope.launch {
            try {
                task()
            } catch (e: Throwable) {
                exceptionHandler?.let { it(e) }
            }
        }
        mJobs.add(job)
        return job
    }
}